package com.lukebang.service.serviceImpl;

import java.math.RoundingMode;
import java.security.interfaces.RSAPrivateKey;
import java.text.DecimalFormat;
import java.util.Date;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import com.lukebang.util.BuluResult;
import com.lukebang.util.DateUtils;
import com.lukebang.util.LuKeOrderNoUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.lukebang.constant.Const;
import com.lukebang.constant.PayMethod;
import com.lukebang.constant.TypeOfIndent;
import com.lukebang.dao.MerchantDAO;
import com.lukebang.dao.MerchantsWalletRecordDAO;
import com.lukebang.pojo.Merchant;
import com.lukebang.pojo.MerchantsWalletRecord;
import com.lukebang.service.IMerchantService;
import com.lukebang.util.MD5Utils;
import com.lukebang.util.RSAUtils;
import com.lukebang.util.ClothCurtain.Arith;
import com.lukebang.util.alipay.AlipayConfig;

/**
 * 
 * MerchantServiceImpl 上午11:16:17
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */
@Service("merchantSER")
public class MerchantServiceImpl implements IMerchantService {
	private static Logger logger = LogManager.getLogger(MerchantServiceImpl.class.getName());

	@Resource
	MerchantDAO merchantDAO;
	@Resource
	MerchantsWalletRecordDAO merchantsWalletRecordDAO;

	@Override
	public boolean login(String phone, String password, HttpSession session) {
		Merchant merchant = merchantDAO.selectMerchantByPhone(phone);
		if (merchantDAO.selectMerchantByPhone(phone) != null) {
			// 获取加的盐值
			String salt = merchant.getWeiyi();
			String saltPassword = MD5Utils.GetMD5Code(password + salt);
			if (saltPassword.equals(merchant.getPassword())) {
				session.setAttribute(Const.SESSION_USER, merchant);
				return true;
			}
			return false;
		} else {
			return false;
		}
	}

	@Override
	public double selectWallet(HttpSession session) {
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		return merchantDAO.selectWallet(merchant.getMerchantsId());
	}

	@Override
	public Map<String, Object> selectInitialInfomation(HttpSession session) {
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		merchant = merchantDAO.selectMerchantByPrimaryKey(merchant.getMerchantsId());
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("wallet", merchant.getWallet());
		retMap.put("avatar", merchant.getHeadImg());
		retMap.put("zhifubao", merchant.getZhifubao());
		retMap.put("baoName", merchant.getBaoName());
		System.out.println("getInitialInfomation===="+retMap);
		return retMap;
	}

	@Override
	public Integer insertMerchant(Merchant merchant) {
		Integer phoneCount = selectCountByPhone(merchant.getPhone());
		if (phoneCount != 0) {
			return 0;
		}
		if (merchant != null) {
			// 判断下验证码对不对，session是否过期
			String weiyi = MD5Utils.getUUID();
			merchant.setPassword(MD5Utils.GetMD5Code(merchant.getPassword() + weiyi));
			merchant.setWeiyi(weiyi);
			merchant.setJoin_date(new Date());
		}
		return merchantDAO.insertMerchant(merchant);
	}

	@Override
	public Integer selectCountByPhone(String phone) {
		return merchantDAO.selectCountByPhone(phone);
	}

	@Override
	public Integer modifyByPhone(Merchant merchant) {
		String weiyi = MD5Utils.getUUID();
		merchant.setPassword(MD5Utils.GetMD5Code(merchant.getPassword() + weiyi));
		merchant.setWeiyi(weiyi);
		return merchantDAO.modifyByPhone(merchant);
	}

	/**
	 * 提现啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦
	 */
	@Override
	public BuluResult alipyWithdrawal(HttpServletRequest request, HttpSession session, Double withdrawMoney,
			String zhifubao, String name, Integer status, String password) {
		// TODO Auto-generated method stub
		System.out.println("^^^^^^^^^^^提现啦^^^^^^^^^^^^^^^^");
		BuluResult buluResult = new BuluResult();
		// 当前登录的用户
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		System.out.println("商家啦啦啦啦啦啦啦："+merchant);
		// 1、解密传输密码
		String descrypedPwd = null;
		RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
		try {
			descrypedPwd = RSAUtils.decryptByPrivateKey(password, privateKey);// 解密后的密码,password
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 比对密码
		Map<String, Object> map = merchantDAO.selectMerchantPwd(merchant.getMerchantsId());
		String saltPassword = MD5Utils.GetMD5Code(descrypedPwd + merchant.getWeiyi());
		if (saltPassword.equals(map.get("password"))) {
			Double wallet = merchantDAO.selectWallet(merchant.getMerchantsId());
			// 2、比较输入金额和钱包
			if (wallet >= withdrawMoney) {
				// a、查询出支付宝账号
				String merchantsAlipayAccount = merchantDAO.selectAlipayAccountByMerchantsId(merchant.getMerchantsId());
				System.out.println("支付宝账号"+merchantsAlipayAccount+",支付宝姓名:"+name);
				if (merchantsAlipayAccount==null || merchant.getName()==null) {
					//如果是第一次提现，先更新用户输入的支付宝账号和姓名
					Map<String, Object> alipyInfo=new HashMap<>();
					alipyInfo.put("merchantsId", merchant.getMerchantsId());
					alipyInfo.put("zhifubao", zhifubao);
					alipyInfo.put("baoName", name);
					System.out.println("第一次提现先保存下支付宝账号");
					merchantDAO.updateMerchantsZFBAccountAndBaoName(alipyInfo);
				}
				String merchantsAlipayAccount2 = merchantDAO.selectAlipayAccountByMerchantsId(merchant.getMerchantsId());
				System.out.println("查出来====="+merchantsAlipayAccount2);
				// b、比较支付宝账号和姓名是否一致
				if (merchantsAlipayAccount2.equals(zhifubao) && merchant.getName().equals(name)) {
					// 3、开始提现,并做交易记录
					MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
					merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
					// 提现
					merchantsWalletRecord.setType(TypeOfIndent.WITHDRAWALS.getIndex());
					// 提现金额（商家或者个人提现）
					merchantsWalletRecord.setWalletWithdrawals(withdrawMoney);
					merchantsWalletRecord.setRecordBeginTime(DateUtils.getDateTime());
					// 公司对钱包记录的流水号,无论余额支付还是支付宝支付都有
					merchantsWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
							PayMethod.ALIPAY.getIndex(), TypeOfIndent.WITHDRAWALS.getIndex()));
					if (status == 1) {// 支付宝方式
						merchantsWalletRecord.setMethod(PayMethod.ALIPAY.getMethod());
						merchantsWalletRecord.setRemark("支付宝提现");
						// 支付宝账号
						merchantsWalletRecord.setAlipayNum(zhifubao);
						// 调用支付宝转账接口
						System.out.println("调用支付宝转账接口啦啦噜啦啦啦拉拉拉拉拉拉拉拉拉拉拉拉拉拉拉");
						AlipayClient alipayClient0 = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
								AlipayConfig.app_id, AlipayConfig.app_private_key, "json", "utf-8",
								AlipayConfig.alipay_public_key, "RSA2");
						AlipayFundTransToaccountTransferRequest request1 = new AlipayFundTransToaccountTransferRequest();
						AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
						// 鹿客家居的唯一提现流水号
						model.setOutBizNo(merchantsWalletRecord.getOrderNo());
						// 收款方账户类型。
						model.setPayeeType("ALIPAY_LOGONID");
						// 收款方账户。
						model.setPayeeAccount(zhifubao);
						// 转账金额
						DecimalFormat formater = new DecimalFormat("#0.#");
						formater.setRoundingMode(RoundingMode.FLOOR);
						logger.error(formater.format(Arith.mul(withdrawMoney, Arith.sub(1, 0.006))));
						model.setAmount(formater.format(Arith.mul(withdrawMoney, Arith.sub(1, 0.006))));
						// 付款方真实姓名
						model.setPayerShowName("郑州鹿客互联网科技有限公司");
						// 收款方真实姓名（最长支持100个英文/50个汉字）。
						model.setPayeeRealName(name);
						// 转账备注
						model.setRemark("顾客个人提现");
						// 加入请求头
						request1.setBizModel(model);
						AlipayFundTransToaccountTransferResponse response = null;
						
						try {
							Thread.sleep(3000);
							response = alipayClient0.execute(request1);
							if (response.isSuccess()) {// 请求成功
								// 返回已经处理成功信息
								JSONObject jsonObject = JSONObject.parseObject(response.getBody());
								logger.error(jsonObject.get("alipay_fund_trans_toaccount_transfer_response"));
								buluResult.setStatus(0);
								buluResult.setMessage("提现成功");
								// {"msg":"Success","pay_date":"2017-04-15
								// 12:34:40","code":"10000","order_fee":"0.00","out_biz_no":"xia12345678890","order_id":"20170415110070001502310004692121","status":"SUCCESS"}
							} else {
								if (response.getCode().equals("40004")
										&& response.getSubCode().equals("PAYER_BALANCE_NOT_ENOUGH")) {
									buluResult.setStatus(2);
									buluResult.setMessage("提现申请中,请耐心等待...");
									return buluResult;
								}
								BuluResult buluResult2 = alipayFundTransOrderQuery(merchantsWalletRecord, merchant);
								if (buluResult2.getStatus() == 0) {
									buluResult.setStatus(0);
									buluResult.setMessage("提现成功");
									System.out.println("提现成功咕咕咕咕过过过过过");
								} else {
									// 返回转账失败信息
									JSONObject jsonObject = JSONObject.parseObject(response.getBody());
									logger.error(jsonObject.get("alipay_fund_trans_toaccount_transfer_response"));
									buluResult.setStatus(1);
									buluResult.setMessage(response.getSubMsg());
								}
							}
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}

						merchantsWalletRecord.setStatus(1);
						merchantsWalletRecord.setRecordEndTime(DateUtils.getDateTime());
						merchantsWalletRecord.setFinalLostMoney(withdrawMoney);
						System.out.println("调用支付宝转账接口     END 啦啦噜啦啦啦拉拉拉拉拉拉拉拉拉拉拉拉拉拉拉");
						// 插入记录
						merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
						System.out.println("做交易记录啦     END 啦啦噜啦啦啦拉拉拉拉拉拉拉拉拉拉拉拉拉拉拉");
						//4、提现成功以后钱包余额应减少相应的金额，更新钱包。
						Double newMerchantsWallet = Arith.sub(merchant.getWallet(), withdrawMoney);
						Map<String, Object> mapWallet = new HashMap<>();
						mapWallet.put("merchantsId", merchant.getMerchantsId());
						mapWallet.put("wallet", newMerchantsWallet);
						merchantDAO.updateMerchantWithDrawWallet(mapWallet);
						System.out.println("更新钱包完成啦啦啦啦啦啦");
						buluResult.setStatus(0);
						buluResult.setMessage("提现成功!");
					} else {
						buluResult.setStatus(1);
						buluResult.setMessage("其他提现方式正在开通，敬请期待!");
					}
				} else {
					buluResult.setStatus(1);
					buluResult.setMessage("提现人姓名或者支付宝账号不对");
				}
			} else {
				buluResult.setStatus(1);
				buluResult.setMessage("提现金额大于钱包余额，钱包余额不足，不能完成提现!");
			}
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("密码不正确!");
		}

		return buluResult;
	}

	/**
	 * 提现业务的防止幂等现象
	 *
	 */
	private BuluResult alipayFundTransOrderQuery(MerchantsWalletRecord customerWalletRecord, Merchant merchant) {
		logger.error("=======================================顾客提现查看是否出现幂等现象=========================================");
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				AlipayConfig.app_id, AlipayConfig.app_private_key, "json", "utf-8", AlipayConfig.alipay_public_key,
				"RSA2");
		BuluResult buluResult = new BuluResult();
		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		AlipayFundTransOrderQueryModel model = new AlipayFundTransOrderQueryModel();
		model.setOutBizNo(customerWalletRecord.getOrderNo());
		request.setBizModel(model);
		AlipayFundTransOrderQueryResponse response = null;
		try {
			response = alipayClient.execute(request);
			if (response.isSuccess()) {
				logger.error("在支付宝找到了本次订单，说明已经转过了出现了幂等现象，更新数据库数据返回转账结束标志");
				logger.error(response.getBody());
				// 请求成功，把该次请求插入数据库
				// 返回已经处理成功信息
				logger.error(JSONObject.parseObject(response.getBody())
						.get("alipay_fund_trans_toaccount_transfer_response"));
				buluResult.setStatus(0);
				buluResult.setMessage("提现成功");
				// {"msg":"Success","pay_date":"2017-04-15
				// 12:34:40","code":"10000","order_fee":"0.00","out_biz_no":"xia12345678890","order_id":"20170415110070001502310004692121","status":"SUCCESS"}
			} else {
				// 数据库中插入一条没有处理的提现记录(无论提现是否成功都要保存提现记录)
				// {"msg":"Business
				// Failed","code":"40004","sub_msg":"转账订单不存在","sub_code":"ORDER_NOT_EXIST"}
				logger.error("在支付宝没有查到本次转账订单，本次转账在支付宝方没有处理也没有出现幂等现象");
				JSONObject jsonObject = JSONObject.parseObject(response.getBody());
				logger.error(jsonObject.get("alipay_fund_trans_order_query_response"));
				buluResult.setStatus(1);
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return buluResult;
	}

}
